﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.zyy;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Writer.API.Appliaction.Commends.Zyy.Returns;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Writer.API.Appliaction.CommandHandlers.Zyy.ReturnApplications
{
    public class UpdateReturnCheHandler : IRequestHandler<UpdateReturnCheCommand, ApiResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public UpdateReturnCheHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }


        public async Task<ApiResult<int>> Handle(UpdateReturnCheCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> result = new ApiResult<int>();
                var data = mapper.Map<ReturnApplication>(request);
                var existingEntity = await db.Queryable<ReturnApplication>()
                                    .Where(x => x.ReturnApplicationId == request.ReturnApplicationId)
                                    .FirstAsync(cancellationToken);
                if (existingEntity==null)
                {
                    result.Code = ApiEnums.修改失败 ;
                    result.Msg = "未找到对应的退货申请记录";
                    return result;
                }
                var updateResult = await db.Updateable<ReturnApplication>()
                             .SetColumns(x => x.Status == request.Status)
                       
                             .Where(x => x.ReturnApplicationId == request.ReturnApplicationId)
                             .ExecuteCommandAsync(cancellationToken);

                // 4. 处理结果
                if (updateResult > 0)
                {
                    result.Code = ApiEnums.修改成功;
                    result.Msg = "状态更新成功";
                    result.Data = existingEntity.ReturnApplicationId;

                    // 可选：发布状态变更事件
                    // await mediator.Publish(new ReturnStatusChangedEvent(existingEntity.Id, existingEntity.Status, request.NewStatus));
                }
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
